import { Select } from 'antd';
import React, { useState, useEffect, useMemo } from 'react';
import { SettingsPanel } from '../SettingsPanel';
import { useUserSettingCustomer } from '@app-base/common/providers/userSettingProvider';
import { OperationConfigItem } from './operation-config-item';
import { httpSettingApi } from '@app-base/server/setting-http';
import { MessageTip } from '@app-base/common/utils/MessageTip';

const OPERATION_TYPES: CmdSettingSpace.OperationType[] = [
  'pan',
  'zoom',
  'rotate',
];

const OPERATION_LABELS: Record<CmdSettingSpace.OperationType, string> = {
  pan: '平移',
  zoom: '缩放',
  rotate: '旋转',
};

const MOUSE_OPTIONS = [
  'mouse-middle-move',
  'mouse-middle-click',
  'mouse-right-click',
  'mouse-middle-right-click',
];

const CAD_OPERATION_CONFIGS: Record<
  CmdSettingSpace.CadType,
  CmdSettingSpace.CadOperationConfig
> = {
  NEXT: {
    pan: { key: '', mouse: 'mouse-middle-click' },
    zoom: { key: '', mouse: 'mouse-middle-move' },
    rotate: { key: '', mouse: 'mouse-right-click' },
  },
  CATIA: {
    pan: { key: '', mouse: 'mouse-middle-click' },
    zoom: {
      key: '',
      mouse: 'mouse-left-middle-short',
      mouseSecond: 'mouse-middle-right-short',
    },
    rotate: {
      key: '',
      mouse: 'mouse-left-middle-long',
      mouseSecond: 'mouse-middle-right-long',
    },
  },
  SolidWorks: {
    pan: { key: 'CTRL', mouse: 'mouse-middle-click' },
    zoom: { key: '', mouse: 'mouse-middle-move' },
    rotate: { key: '', mouse: 'mouse-middle-click' },
  },
  'UG/NX': {
    pan: { key: '', mouse: 'mouse-middle-right-click' },
    zoom: { key: '', mouse: 'mouse-middle-move' },
    rotate: { key: '', mouse: 'mouse-middle-click' },
  },
  Creo: {
    pan: { key: 'SHIFT', mouse: 'mouse-middle-click' },
    zoom: { key: '', mouse: 'mouse-middle-move' },
    rotate: { key: '', mouse: 'mouse-middle-click' },
  },
  Inventor: {
    pan: { key: '', mouse: 'mouse-middle-click' },
    zoom: { key: '', mouse: 'mouse-middle-move' },
    rotate: { key: 'SHIFT', mouse: 'mouse-middle-click' },
  },
  Custom: {
    pan: { key: '', mouse: 'mouse-middle-click' },
    zoom: { key: '', mouse: 'mouse-middle-move' },
    rotate: { key: '', mouse: 'mouse-right-click' },
  },
};

const CAD_TYPE_OPTIONS = Object.keys(CAD_OPERATION_CONFIGS).map((type) => ({
  value: type,
  label: type,
}));

interface OperatingHabitsProps {
  onCloseDialog?: () => void;
}

const OperatingHabits: React.FC<OperatingHabitsProps> = ({ onCloseDialog }) => {
  const { userHabit, setUserHabit } = useUserSettingCustomer();

  const [toolbarPosition, setToolbarPosition] = useState<'top' | 'bottom'>(
    userHabit?.toolbarPosition || 'bottom',
  );
  const [cadType, setCadType] = useState<CmdSettingSpace.CadType>(
    (userHabit?.cadType as CmdSettingSpace.CadType) || 'NEXT',
  );
  const [customConfig, setCustomConfig] =
    useState<CmdSettingSpace.CadOperationConfig>(
      (userHabit?.customConfig as CmdSettingSpace.CadOperationConfig) ||
        CAD_OPERATION_CONFIGS.Custom,
    );
  const [operationError, setOperationError] = useState('');
  const [loading, setLoading] = useState(false);

  const currentCadConfig = useMemo(
    () => CAD_OPERATION_CONFIGS[cadType],
    [cadType],
  );

  useEffect(() => {
    if (userHabit) {
      setToolbarPosition(userHabit.toolbarPosition);
      setCadType(userHabit.cadType as CmdSettingSpace.CadType);
      if (userHabit.customConfig) {
        setCustomConfig(
          userHabit.customConfig as CmdSettingSpace.CadOperationConfig,
        );
      }
    }
  }, [userHabit]);

  // 验证是否冲突
  function validateOperations(
    config: CmdSettingSpace.CadOperationConfig,
  ): boolean {
    for (let i = 0; i < OPERATION_TYPES.length; i++) {
      for (let j = i + 1; j < OPERATION_TYPES.length; j++) {
        const op1 = config[OPERATION_TYPES[i]];
        const op2 = config[OPERATION_TYPES[j]];
        if (op1.key === op2.key && op1.mouse === op2.mouse) {
          return false;
        }
      }
    }
    return true;
  }

  function updateCustomConfig(
    operation: CmdSettingSpace.OperationType,
    type: 'key' | 'mouse',
    value: string,
  ): void {
    const newConfig = {
      ...customConfig,
      [operation]: { ...customConfig[operation], [type]: value },
    };

    if (validateOperations(newConfig)) {
      setOperationError('');
      setCustomConfig(newConfig);
    } else {
      setOperationError('平移、缩放和旋转的操作设置不能相同');
    }
  }

  async function handleSave(): Promise<void> {
    try {
      setLoading(true);

      const configData = {
        toolbarPosition,
        cadType,
        customConfig: cadType === 'Custom' ? customConfig : null,
      };

      const electronAPI = (window as any).electronAPI;
      if (electronAPI?.saveSettings) {
        electronAPI.saveSettings(configData);
      }

      await httpSettingApi.saveUserHabitDetail(configData);

      setUserHabit({
        toolbarPosition,
        cadType,
        customConfig: cadType === 'Custom' ? customConfig : undefined,
      });

      MessageTip.success('操作习惯设置已保存');
    } catch (err) {
      MessageTip.error('保存失败，请重试');
    } finally {
      setLoading(false);
    }
  }

  function handleRestoreDefaults(): void {
    setCadType('NEXT');
    setToolbarPosition('bottom');
    setCustomConfig(CAD_OPERATION_CONFIGS.Custom);
    setOperationError('');
    MessageTip.info('已恢复默认设置，保存后生效');
  }

  function handleCadTypeChange(value: CmdSettingSpace.CadType): void {
    setCadType(value);
    if (value !== 'Custom') {
      setOperationError('');
    }
  }

  return (
    <SettingsPanel
      title='操作习惯'
      onSave={handleSave}
      onCancel={onCloseDialog}
      onRestoreDefaults={handleRestoreDefaults}
      isSaveDisabled={loading || operationError !== ''}
    >
      <div className='min-h-[400px]'>
        <div className='my-2'>
          <Select
            value={cadType}
            style={{ width: 200 }}
            onChange={handleCadTypeChange}
            options={CAD_TYPE_OPTIONS}
            disabled={loading}
          />
        </div>

        <div className='flex flex-col gap-5 mt-5'>
          {OPERATION_TYPES.map((op) => (
            <OperationConfigItem
              key={op}
              operation={op}
              label={OPERATION_LABELS[op]}
              isCustom={cadType === 'Custom'}
              config={
                cadType === 'Custom' ? customConfig[op] : currentCadConfig[op]
              }
              updateCustomConfig={updateCustomConfig}
              mouseOptions={MOUSE_OPTIONS}
            />
          ))}
        </div>

        {operationError && (
          <div className='my-2 text-sm text-red-500'>{operationError}</div>
        )}
      </div>
    </SettingsPanel>
  );
};

export default OperatingHabits;
